# 改变文件大小，并将对应xml文件中的数值也进行改变
from PIL import  Image
#import cv2
import os
import re

width_look = re.compile(r'\t\t<width>\d+</width>')
height_look = re.compile(r'\t\t<height>\d+</height>')

def creatcopypath(file):
    if not os.path.exists(file):
        os.mkdir(file)
        return file + '/'
    else:
        return file + '/'

def pic_handle(pathin, pathout):
    #img = cv2.imread(pathin)
    img = Image.open(pathin)
    #[img_hei, img_wid] = img.shape[0:2]
    [img_hei,img_wid] = img.size
    #cv2.imwrite(pathout, img.resize(416, 416))
    img.save(pathout)
    change_prop = [416 / img_hei, 416 / img_wid]
    return change_prop


def xml_handle(pathin, pathout, change_prop):

    with open(pathin,'r') as f:
        filelist = f.readlines()
        for i in range(len(filelist)):
            if width_look.match(filelist[i]):
                new_w = str(int(int(filelist[i].split('>')[1].split('<')[0])*change_prop[1]))
                new_w_str = '\t\t<width>' + new_w + '</width>'
                filelist[i] = width_look.sub(new_w_str, filelist[i])
            if height_look.match(filelist[i]):
                new_h = str(int(int(filelist[i].split('>')[1].split('<')[0])*change_prop[0]))
                new_h_str = '\t\t<height>' + new_h + '</height>'
                filelist[i] = width_look.sub(new_h_str, filelist[i])
    with open(pathout, 'w') as f:
        f.writelines(filelist)
if __name__ == '__main__':
    path = '/Users/jiangce/Desktop/车型识别/VOCdevkit/'
    path_img_copy = path + 'img2'
    path_xml_copy = path + 'xml2'
    path_img_copy = creatcopypath(path_img_copy)
    path_xml_copy = creatcopypath(path_xml_copy)
    path_img = path + 'img/'
    path_xml = path + 'xml/'
    img_list = os.listdir(path_img)
    #xml_list = os.listdir(path_xml)
    i = 0
    for img in img_list:
        change_prop = pic_handle(path_img + img,path_img_copy+img)
        xml = img.split('.')[0] + '.xml'
        xml_in = path_xml + xml
        xml_out = path_xml_copy + xml
        xml_handle(xml_in,xml_out,change_prop)
        print("i is {}".format(i))
        i+=1



#xml_handle('/Users/jiangce/Desktop/pycharm/Company/t_106988125402.xml', '/Users/jiangce/Desktop/pycharm/Company/test.xml',[1.2,1.2])


